package com.xuan.yubi.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class EasyExcelUtils {


    public static String excelToCsv(MultipartFile multipartFile, ExcelTypeEnum excelTypeEnum){
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcelFactory.read(multipartFile.getInputStream())
                    .excelType(excelTypeEnum)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("excelToCsv error: ", e);
        }
        if (CollectionUtils.isEmpty(list)) {
            return "";
        }

        // 将表格数据转化为 csv 格式
        StringBuilder res = new StringBuilder();
        // 运行时类型为 LinkedHashMap
        for (Map<Integer, String> dataMap : list) {
            List<String> dataList = dataMap.values().stream().
                    filter(ObjectUtils::isNotEmpty)
                    .map(s -> s.replace(",", ""))
                    .collect(Collectors.toList());
            res.append(StringUtils.join(dataList, ",")).append('\n');
        }
        return res.toString();
    }


}
